package com.woniu.service.healthSystem.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.mapper.healthSystem.PermissionMapperGb;
import com.woniu.model.healthSystem.entity.Permission;
import com.woniu.model.healthSystem.vo.PageVo;
import com.woniu.model.healthSystem.vo.PermissonMenuVo;
import com.woniu.service.healthSystem.IPermissionServiceGb;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限等级分配表 服务实现类
 * </p>
 *
 * @author gb
 * @since 2023-10-19
 */
@Service
public class PermissionServiceImplGb extends ServiceImpl<PermissionMapperGb, Permission> implements IPermissionServiceGb {

    @Override
    public List<PermissonMenuVo> findPermissionByManagerId(Long managerId) {
        List<Permission> permissions = baseMapper.findPermissionByManagerId(managerId);

        //封装权限  子权限的Vo
        List<PermissonMenuVo> voList = convertPermissionToVo(permissions);
        return voList;
    }

    @Override
    public PageVo findAll(Integer pageNum, Integer pageSize, String permissionName) {
        LambdaQueryWrapper<Permission> wrapper = Wrappers.lambdaQuery(Permission.class);
        wrapper.eq(StringUtils.hasText(permissionName),Permission::getPermissionName,permissionName);
        Page<Permission> page = baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return new PageVo<>(page.getRecords(),page.getTotal());
    }

    @Override
    public List<PermissonMenuVo> treeList() {
        // 查询所有的权限
        List<Permission> permissions = this.list();
        // 封装权限、子权限的vo
        List<PermissonMenuVo> voList = convertPermissionToVo(permissions);
        return voList;
    }

    private List<PermissonMenuVo> convertPermissionToVo(List<Permission> permissions) {
        //先过滤一级菜单
        List<PermissonMenuVo> voList = permissions.stream().filter(e -> e.getParentId() == -1).map(e -> {
            PermissonMenuVo pmv = new PermissonMenuVo();
            pmv.setId(e.getId());
            pmv.setPermissionName(e.getPermissionName());
            //再过滤一次找到二级菜单，并放置到一级菜单中去
            List<PermissonMenuVo> children = permissions.stream().filter(m -> m.getParentId() == e.getId()).map(m -> {
                PermissonMenuVo pmvc = new PermissonMenuVo();
                pmvc.setId(m.getId());
                pmvc.setPermissionName(m.getPermissionName());
                pmvc.setUrl(m.getUrl());
                return pmvc;
            }).collect(Collectors.toList());
            pmv.setChildren(children);
            return pmv;
        }).collect(Collectors.toList());
        return voList;
    }
}
